# 编译工具链前缀
PREFIX = ~/zWCH/MRS_Toolchain_Linux_x64_V1.90/RISC-V_Embedded_GCC/bin/riscv-none-embed-
# 编译目标
BUILD_TARGET =zhcled
# 编译的目标目录
BUILD_DIR = 
#BUILD_DIR = build
# 设置调试标志
DEBUG = 1
# 架构相关选项
ARCH = -march=rv32imac -mabi=ilp32
# 系统优化选项配置
OPT = 

# C源文件目录
C_SOURCES =$(shell find . -name "*.c" ) 
C_SOURCES +=$(shell find ../common -name "*.c" | grep -v NetLib) 

ASM_SOURCES =startup_ch32v30x_D8.s

C_INCLUDES = \
-I../common/Peripheral/inc \
-I../common/Core/ \
-I. \

# 编译器定义
CC = $(PREFIX)gcc
AS = $(PREFIX)as
#AS = $(PREFIX)gcc -x assembler-with-cpp
CP = $(PREFIX)objcopy
SZ = $(PREFIX)size

HEX = $(CP) -O ihex
BIN = $(CP) -O binary -S

# 编译器选项
CFLAGS = $(ARCH) $(OPT) $(C_INCLUDES) -MMD -MP -MF"$(@:%.o=%.d)"
ASFLAGS = $(ARCH) 

# 链接文件定义
LDSCRIPT = Link.ld
# 链接库定义
LIBS = -lc -lm -lnosys

# 链接选项
LDFLAGS = $(ARCH) -mno-save-restore -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -Wunused -Wuninitialized -nostartfiles -Xlinker --gc-sections --specs=nosys.specs -Wl,-Map=$(TARGET).map -T$(LDSCRIPT) $(LIBS)

# 调试选项
ifeq ($(DEBUG), 1)
CFLAGS += -g
LDFLAGS += -g
endif


# 指定目标文件列表(C文件所构建)
#OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
OBJECTS=$(ASM_SOURCES:%.s=%.o)
OBJECTS+=$(C_SOURCES:%.c=%.o)

# 完整构建需要构建elf可执行程序，hex文件和bin文件
all:$(BUILD_TARGET).elf $(BUILD_TARGET).hex $(BUILD_TARGET).bin


# 对所有的汇编文件，全部编译为目标文件
$(BUILD_DIR)/%.o:%.s Makefile | $(BUILD_DIR)
	date
	#$(AS)   $< -o $@
# 对所有的C文件，全部编译为目标文件
$(BUILD_DIR)/%.o:%.c Makefile | $(BUILD_DIR)
	$(CC) -c $(CFLAGS) $< -o $@

# 链接目标文件为可执行程序
$(BUILD_TARGET).elf:$(OBJECTS) 
	$(CC) $(LDFLAGS) $(OBJECTS) -o $@
	$(SZ) $@

$(BUILD_TARGET).hex:$(BUILD_TARGET).elf 
	$(CP)  $(BUILD_TARGET).elf $(BUILD_TARGET).hex -O ihex
$(BUILD_TARGET).bin:$(BUILD_TARGET).elf 
	$(CP)  $(BUILD_TARGET).elf $(BUILD_TARGET).bin -Obinary
socat:
	sudo socat tcp4-listen:4160,fork,reuseaddr FILE:/dev/ttyACM0,b9600,echo=0,raw

clean:
	rm -rf $(BUILD_TARGET).* *.o *.d *.hex *.bin *.elf .map
	find ../ | grep "\.o" | grep -v NetLib | xargs -i rm {}
	find ../ | grep "\.d" | xargs -i rm {}
shaolu:
	sudo ~/zWCH/MRS_Toolchain_Linux_x64_V1.90/OpenOCD/bin/openocd  -f  ~/zWCH/MRS_Toolchain_Linux_x64_V1.90/OpenOCD/bin/wch-riscv.cfg -c init -c halt -c "flash erase_sector wch_riscv     0 last" -c "program zhcled.bin" -c reset
	#sudo ../../../MRS_Toolchain_Linux_x64_V1.90/OpenOCD/bin/openocd  -f  ../../../MRS_Toolchain_Linux_x64_V1.90/OpenOCD/bin/wch-riscv.cfg -c init -c halt -c "flash erase_sector wch_riscv     0 last" -c "program zhcled.bin" -c "verify_image zhcled.bin" -c wlink_reset_resume 
